package com.hd.trans.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.databinding.ActivityEditTransResultBinding
import com.hd.trans.db.bean.FileTranslateRecord
import com.hd.trans.framework.click.XClickUtil
import com.hd.trans.framework.dialog.TipsNormalDlg
import com.hd.trans.framework.rom.IOUtils
import com.hd.trans.ui.base.BaseActivity
import com.hd.trans.ui.model.PictureTransModel
import com.hd.trans.utils.Constant
import com.hd.trans.utils.TrackerForTrans
import java.io.FileInputStream

class EditTransResultActivity: BaseActivity(), View.OnClickListener {
    lateinit var fileTranslateRecord: FileTranslateRecord
    private var clickY = 0f
    private var createTime: Long = -1L
    private var isTransPart: Boolean = false
    private var editContent: String = ""
    lateinit var mDataModel: PictureTransModel
    lateinit var mDataBinding: ActivityEditTransResultBinding

    override fun getLayoutId(): Int {
        return R.layout.activity_edit_trans_result
    }

    companion object {

        @JvmStatic
        fun open(context: Activity, id: Long, isTransPart: Boolean, requestCode: Int) {
            val intent = Intent(context, EditTransResultActivity::class.java)
            intent.putExtra("createTime", id)
            intent.putExtra("isTransPart", isTransPart)
            context.startActivityForResult(intent,requestCode)
        }
    }

    private val dialog by lazy {
        TipsNormalDlg.newInstance(TipsNormalDlg.TipsDlgData.Builder()
            .content(resources.getString(R.string.confirm_tip4))
            .cancelStr(resources.getString(R.string.exit))
            .okStr(resources.getString(R.string.cancel))
            .canceledOnTouchOutside(false)
            .build()).apply {
            setOnPositiveClick {
                //nothing to do
            }
            setOnNegativeClick {

                finish()
            }
        }

    }

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        createTime = intent.getLongExtra("createTime",-1L)
        isTransPart = intent.getBooleanExtra("isTransPart", false)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_trans_result)
        mDataModel = ViewModelProvider(this).get(PictureTransModel::class.java)
        //视图埋点
        TranslationInterior.getTrackerListener().view("${TrackerForTrans.PZFY}${if(isTransPart) "译文编辑" else "原文编辑"}")

        initView()
        initData()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        mDataBinding.apply {
            click = this@EditTransResultActivity
            activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
            middleView.text = if(isTransPart) getString(R.string.edit_translate) else getString(R.string.edit_original)
            etContent.setOnTouchListener { _, event ->
                event.x
                when (event.action) {
                    MotionEvent.ACTION_UP -> {
                        clickY = event.rawY
                    }
                }
                false
            }
            //界面出现变动都会调用这个监听事件
            spaceDownEdit.viewTreeObserver
                .addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                    private var lastHeight = 0
                    private var lastScrollY = 0
                    override fun onGlobalLayout() {
                        val rect = Rect()//可见范围四个点
                        val rootView = activity.window.decorView
                        rootView.getWindowVisibleDisplayFrame(rect)
                        //不可见高度　rootInvisibleHeight＝屏幕的高度 - 屏幕顶部到底部NavigationBar（安卓三大金刚）上边Y坐标
                        val rootInvisibleHeight: Int =
                            rootView.rootView.height - rect.bottom
                        if (lastHeight == rootInvisibleHeight) {
                            return
                        }
                        lastHeight = rootInvisibleHeight
                        // 键盘弹出时rootInvisibleHeight=键盘高度 + 底部NavigationBar（安卓三大金刚）高度
                        // 键盘没弹出时，rootInvisibleHeight=底部NavigationBar（安卓三大金刚）高度,
                        // 如果三大金刚是屏幕外的实体按键（比如三星S6，魅族，华为Mate10之类的）rootInvisibleHeight=0
                        // 三大金刚一般高度150左右，基本在200以内，就用200做比较就可以了。
                        // 键盘弹出时rootInvisibleHeight=键盘高度 + 底部NavigationBar（安卓三大金刚）高度
                        // 键盘没弹出时，rootInvisibleHeight=底部NavigationBar（安卓三大金刚）高度,
                        // 如果三大金刚是屏幕外的实体按键（比如三星S6，魅族，华为Mate10之类的）rootInvisibleHeight=0
                        // 三大金刚一般高度150左右，基本在200以内，就用200做比较就可以了。
                        val params = spaceDownEdit.layoutParams
                        if (rootInvisibleHeight < 200) {
                            // 键盘收起
                            params.height = resources.getDimensionPixelOffset(R.dimen.dp_0dp)
                            spaceDownEdit.layoutParams = params
                            spaceDownEdit.invalidate()
                            nestedScrollView.postDelayed({
                                nestedScrollView.scrollTo(0,lastScrollY)
                            },100)
                        } else {
                            // 键盘弹出
                            params.height = rootInvisibleHeight
                            lastScrollY = nestedScrollView.scrollY
                            spaceDownEdit.layoutParams = params
                            spaceDownEdit.invalidate()
                            nestedScrollView.postDelayed({
                                if((rootView.rootView.height - clickY) < rootInvisibleHeight)
                                    nestedScrollView.scrollBy(0,
                                        (clickY - rect.bottom + 30).toInt())//30是为了让键盘弹出后，光标不会被键盘挡住,这个值可以根据实际情况调整：误差值
                            },100)
                        }

                    }
                })
        }
    }

    private fun initData() {
        mDataModel.operateRecord.observe(this) {

            fileTranslateRecord = it
            val textFilePath = if (isTransPart) {
                fileTranslateRecord.translateText//译文内容文件路径
            } else {
                fileTranslateRecord.originalText//原文内容文件路径
            }
            try {
                editContent = IOUtils.toString(FileInputStream(textFilePath))
                mDataBinding.etContent.setText(editContent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        mDataModel.getFileTranslateRecordByTime(createTime)
    }

    override fun onBackPressed() {
        if(needSave()){
            //弹窗提示
            showTipsDialog()
        }else{
            super.onBackPressed()
        }
    }

    private fun showTipsDialog() {
        dialog.show(activity.supportFragmentManager, "EditTransResultActivity")
    }

    override fun onClick(v: View) {
        if (XClickUtil.isFastDoubleClick(v, XClickUtil.INTERVAL_MILLIS.toLong())) {
            return
        }
        when(v){
            mDataBinding.leftView -> onBackPressed()
            mDataBinding.rightView -> {
                if(needSave()){
                    val etContentStr = mDataBinding.etContent.text.toString()
                    var intent = Intent()
                    intent.putExtra(Constant.EDIT_CONTENT_RESULT, etContentStr)
                    intent.putExtra(Constant.EDIT_CONTENT_TYPE, isTransPart)
                    setResult(RESULT_OK, intent)
                }

                finish()
            }
        }
    }

    fun needSave(): Boolean {
        val etContentStr = mDataBinding.etContent.text.toString()
        if(!TextUtils.isEmpty(etContentStr) && etContentStr != editContent){
            return true
        }
        return false
    }

}